import datetime
import os
import tempfile

from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from ralph.attachments.helpers import add_attachment_from_disk
from ralph.lib.external_services import ExternalService, obj_to_dict
from ralph.reports.models import Report


def generate_report(name, requester, instances, language, context):
    report = Report.objects.get(name=name)
    template = report.templates.filter(language=language).first()
    if not template:
        template = report.templates.filter(default=True).first()

    template_content = ""
    with open(template.template.path, "rb") as f:
        template_content = f.read()

    attachments = []
    items_per_attachment = 10
    service_pdf = ExternalService("PDF")

    for n in range(0, len(context), items_per_attachment):
        result = service_pdf.run(
            template=template_content,
            data={
                "id": ", ".join(
                    [str(obj.id) for obj in instances[n : n + items_per_attachment]]
                ),
                "now": datetime.datetime.now(),
                "logged_user": obj_to_dict(requester),
                "affected_user": obj_to_dict(instances[0].user),
                "owner": obj_to_dict(instances[0].owner),
                "assets": context[n : n + items_per_attachment],
            },
        )

        filename = (
            "_".join(
                [
                    timezone.now().isoformat()[:10],
                    instances[0].user.get_full_name().lower().replace(" ", "-"),
                    name,
                ]
            )
            + ".pdf"
        )
        with tempfile.TemporaryDirectory() as tmp_dirpath:
            output_path = os.path.join(tmp_dirpath, filename)
            with open(output_path, "wb") as f:
                f.write(result)
            attachments.append(
                add_attachment_from_disk(
                    instances,
                    output_path,
                    requester,
                    _("Document autogenerated by {} transition.").format(name),
                )
            )
    return attachments
